<template>
  <div class="table">
    <div class="title">{{ title }}</div>
    <div style="margin-bottom: 15px">
      <el-input
        v-model="listQuery.q"
        placeholder="请输入搜索内容"
        clearable
        prefix-icon="el-icon-search"
        size="small"
      />
    </div>
    <el-table
      ref="multipleTable"
      :data="list"
      :height="452"
      border
      highlight-current-row
      size="small"
      @select="handleSelect"
      @select-all="handleSelectAll"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="ID" width="100" prop="num" show-overflow-tooltip />
      <el-table-column label="课程名称" min-width="200" prop="name" show-overflow-tooltip />
      <el-table-column label="课程价格（元）" width="120" align="center">
        <template slot-scope="scope">{{ scope.row.price | price }}</template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px">
      <pagination
        :total="filterList.length"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.size"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'TableCol',
  props: {
    data: {
      type: Array,
      default: () => []
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      listQuery: {
        page: 1,
        size: 10,
        q: ''
      },
      multipleSelection: []
    }
  },
  computed: {
    filterList() {
      const data = this.data.filter((item) => {
        if (item.name.includes(this.listQuery.q)) return true
        if (item.num.includes(this.listQuery.q)) return true
        return false
      })
      return data
    },
    list() {
      const data = [...this.filterList]
      const start = (this.listQuery.page - 1) * this.listQuery.size
      const list = data.splice(start, this.listQuery.size)
      this.$nextTick(() => {
        list.forEach((item) => {
          if (this.multipleSelection.includes(item.uuid)) {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          }
        })
      })
      return list
    }
  },
  methods: {
    handleSelect(selection, row) {
      const set = new Set(this.multipleSelection)
      const isCheck = selection.find((item) => item.uuid === row.uuid)
      set[isCheck ? 'add' : 'delete'](row.uuid)
      this.multipleSelection = Array.from(set)
    },
    handleSelectAll(selection) {
      const set = new Set(this.multipleSelection)
      selection.forEach((item) => {
        set[selection.length ? 'add' : 'delete'](item.uuid)
      })
      this.multipleSelection = Array.from(set)
    },
    clearQuery() {
      this.listQuery.q = ''
    },
    clearMultipleSelection() {
      this.multipleSelection.length = 0
    }
  }
}
</script>

<style scoped>
.table {
  width: 540px;
}
.title {
  font-size: 16px;
  margin-bottom: 1em;
}
</style>
